import React, {useEffect, useState} from 'react';
import moment from 'moment';
import styled from 'styled-components';
import {Card, message, Modal, Select, DatePicker} from 'antd';
import IconFont from '../../components/IconFont.jsx';
import {Button, Form, Input} from 'antd';
import {addKey} from '../../components/TableAddKey';
import {
  SyncOutlined,
  BlockOutlined,
  ReconciliationOutlined,
  LogoutOutlined,
  AuditOutlined,
} from '@ant-design/icons';
import axios from '../../http/axios';
const {Option} = Select;
const {RangePicker} = DatePicker;

const StatusboxGreen = styled.div`
  width: 47px;
  height: 47px;
  border-radius: 23px;
  background-color: lightgreen;
`;
const StatusboxBlue = styled.div`
  width: 47px;
  height: 47px;
  border-radius: 23px;
  background-color: #429efd;
`;
const StatusboxRed = styled.div`
  width: 47px;
  height: 47px;
  border-radius: 23px;
  background-color: #f46b6b;
`;
const StatusboxYellow = styled.div`
  width: 47px;
  height: 47px;
  border-radius: 23px;
  background-color: #f5a625;
`;
//外层盒子
const RoomBox = styled.div`
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
`;
const RoomStatus = styled.div`
  position: absolute;
  width: 260px;
  text-align: center;
  top: 10px;
  left: 15px;
  font-size: 28px;
  z-index: 1;
  color: #fff;
  background-color: rgba(168, 168, 168, 0.8);
  border-radius: 5px;
  padding: 5px;
`;
const BtnBox = styled.div`
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
`;

const {Meta} = Card;
export default function Index() {
  const [form] = Form.useForm();
  const [roomlist, setWorkBenchTable] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false); //操作弹窗
  const [operationRomm, setoperationRomm] = useState(''); //暂存房间号
  const {id, status, room_address} = operationRomm;
  const [newRomm, setnewRomm] = useState(''); //换房房间号
  const [changeRoomVisible, setchangeRoomVisible] = useState(''); //换房弹窗
  const [changeroomlist, setchangeroomlist] = useState([]); //换房列表
  const [renewalVisible, setrenewalVisible] = useState(''); //续房弹窗
  const [clearRoomVisible, setclearRoomVisible] = useState(''); //清理完毕弹窗
  const [outRoom, setoutRoom] = useState(''); //清理完毕弹窗
  const [goinghome, setgoinghome] = useState(''); //入住弹窗
  const today = new Date();
  console.log(today);
  useEffect(() => {
    getTableList();
  }, []);
  useEffect(() => {
    if (changeRoomVisible) {
      axios({
        method: 'GET',
        url: '/roomOrders/queryAllEmptyRooms',
        params: {},
      })
        .then((res) => {
          console.log(res);
          setchangeroomlist(res.data);
        })
        .catch((err) => {
          form.resetFields(); // 重置
        });
    }
  }, [changeRoomVisible]);
  const getTableList = () => {
    axios({
      method: 'GET',
      url: '/room/queryAllRooms',
      params: {},
    })
      .then((res) => {
        console.log(res.data.data);
        let db = res.data.data.filter(item =>{
          if(item.shelf_status !== 0){
            return item
          }
        })
        setWorkBenchTable(db);
      })
      .catch((err) => {
        form.resetFields(); // 重置
      });
  };
  const rules = [];
  const showModal = (data) => {
    console.log('设置', data.id);
    setIsModalVisible(true);
    setoperationRomm(data);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    setchangeRoomVisible(false);
    setclearRoomVisible(false);
    setrenewalVisible(false);
    setoutRoom(false);
    setgoinghome(false);
  };

  const statusfn = (status) => {
    //状态图片
    switch (status) {
      case 1:
        return;
      case 2:
        return (
          <RoomStatus>
            <IconFont type="icon-renyuanguanli" style={{fontSize: '100px'}} />
            <p style={{color: '#F46B6B', marginBottom: '0'}}>已入住</p>
          </RoomStatus>
        );
      case 3:
        return (
          <RoomStatus>
            <IconFont type="icon-tejiafangguanli" style={{fontSize: '100px'}} />
            <p style={{color: '#429EFD', marginBottom: '0'}}>已预定</p>
          </RoomStatus>
        );
      case 4:
        return (
          <RoomStatus>
            <IconFont type="icon-dasao" style={{fontSize: '100px'}} />
            <p style={{color: '#F5A625', marginBottom: '0'}}>待清理</p>
          </RoomStatus>
        );
      default:
        return;
    }
  };

  const circular = (status) => {
    //圆
    switch (status) {
      case 1:
        return <StatusboxGreen />;
      case 2:
        return <StatusboxRed />;
      case 3:
        return <StatusboxBlue />;
      case 4:
        return <StatusboxYellow />;
      default:
        return status;
    }
  };

  function disabledDate(current) {
    // Can not select days before today and today
    return current && current < moment().endOf('day');
  }
  const changeBtn = () => {
    setchangeRoomVisible(true);
    //发请求拿数据
  };
  const changeroom = () => {
    //换房事件
    axios({
      method: 'POST',
      url: '/roomOrders/exchangeRoom',
      data: {oldRoomId: id, newRoomId: newRomm, user_id: 1},
    })
      .then((res) => {
        console.log(res);
        getTableList();
        message.success('房间已更改');
      })
      .catch((err) => {});
    console.log('旧房', id, '--', '新房', newRomm);
    setchangeRoomVisible(false);
    setIsModalVisible(false);
  };
  //换房的数据
  const changeRoomSub = (e) => {
    console.log(e);
    setnewRomm(e);
  };
  //提交用户
  const onCreateUser = (value) => {
    axios({
      method: 'POST',
      url: '/roomOrders/checkInRoom',
      data: {roomId: id, user_id: 1},
    })
      .then((res) => {
        getTableList();
        message.success('入住成功');
      })
      .catch((err) => {});
    console.log(value);
    setgoinghome(false);
    setIsModalVisible(false);
  };

  const onCreateXuzhu = (value) => {
    //续房事件
    const createtimer = moment(value.reduce[0]._d).format('YYYY-MM-DD');
    const endtimer = moment(value.reduce[1]._d).format('YYYY-MM-DD');
    console.log(createtimer, endtimer);
    axios({
      method: 'POST',
      url: '/roomOrders/renewalRoom',
      data: {
        roomId: id,
        createTimer: createtimer,
        endTimer: endtimer,
        user_id: 1,
      },
    })
      .then((res) => {
        console.log(res);
        getTableList();
        message.success('续房成功');
      })
      .catch((err) => {});
    setrenewalVisible(false);
  };

  const clearroom = (event) => {
    //打扫和退房发请求

    setoutRoom(false);
    setclearRoomVisible(false);
    setIsModalVisible(false);
    switch (event) {
      case 'clear':
        return axios({
          method: 'POST',
          url: '/roomOrders/changeRoomStatusToEmpty',
          data: {roomId: id},
        })
          .then((res) => {
            console.log(res);
            getTableList();
            message.success('清理完成');
          })
          .catch((err) => {});

      default:
        axios({
          method: 'POST',
          url: '/roomOrders/checkOutRoom',
          data: {roomId: id},
        })
          .then((res) => {
            getTableList();
            message.success('退房成功');
          })
          .catch((err) => {});
    }
  };
  const selectTime = (date, dateString) => {
    console.log(dateString);
    //发请求
    axios({
      method: 'POST',
      url: '/roomOrders/queryReserveRoomOrders',
      data: {selectTime: dateString},
    })
      .then((res) => {
        console.log(res);
        setWorkBenchTable(res.data);
      })
      .catch((err) => {
        console(err);
      });
  };
  return (
    <>
      <DatePicker onChange={selectTime} style={{margin: '20px'}} />
      <RoomBox>
        {roomlist.map((item, index) => {
          return (
            <div
              style={{
                position: 'relative',
                cursor: 'pointer',

                marginBottom: '10px',
              }}
              key={index}
              onClick={() => showModal(item)}
            >
              {statusfn(item.status)}
              <Card
                style={{width: 300}}
                cover={
                  <img
                    style={{height: 180}}
                    alt="example"
                    src={item.room_img}
                  />
                }
              >
                <Meta
                  avatar={circular(item.status)}
                  title={item.room_address}
                  description={item.room_name}
                />
              </Card>
            </div>
          );
        })}
        <Modal
          title="请选择操作"
          visible={isModalVisible}
          onCancel={handleCancel}
          footer={[]}
        >
          <BtnBox>
            {status !== 1 ? (
              <>
                <Button
                  type="primary"
                  shape="round"
                  icon={<SyncOutlined />}
                  style={{
                    margin: '10px 0',
                    width: '200px',
                    background: '#cf1322',
                    border: 'none',
                  }}
                  onClick={changeBtn}
                >
                  换房
                </Button>
                <Button
                  type="primary"
                  shape="round"
                  icon={<BlockOutlined />}
                  style={{
                    margin: '10px 0',
                    width: '200px',
                    background: '#13c2c2',
                    border: 'none',
                  }}
                  onClick={() => {
                    setrenewalVisible(true);
                  }}
                >
                  续房
                </Button>
                <Button
                  type="primary"
                  shape="round"
                  icon={<LogoutOutlined />}
                  style={{
                    margin: '10px 0',
                    width: '200px',
                    background: '#1890ff',
                    border: 'none',
                  }}
                  onClick={() => {
                    setoutRoom(true);
                  }}
                >
                  退房
                </Button>
                <Button
                  type="primary"
                  shape="round"
                  icon={<ReconciliationOutlined />}
                  style={{
                    margin: '10px 0',
                    width: '200px',
                    background: '#faad14',
                    border: 'none',
                  }}
                  onClick={() => {
                    setclearRoomVisible(true);
                  }}
                >
                  清理完毕
                </Button>
              </>
            ) : (
              <Button
                type="primary"
                shape="round"
                icon={<AuditOutlined />}
                style={{
                  margin: '10px 0',
                  width: '200px',
                  background: 'green',
                  border: 'none',
                }}
                onClick={() => setgoinghome(true)}
              >
                入住
              </Button>
            )}
          </BtnBox>
        </Modal>

        <Modal
          title="房间切换"
          visible={changeRoomVisible}
          onOk={changeroom}
          onCancel={handleCancel}
        >
          <p>当前房间号:{room_address}</p>
          <div>
            <IconFont
              type="icon-xianghujiaohuan-shangxia"
              style={{fontSize: '20px'}}
            />
          </div>
          <Select
            showSearch
            placeholder="请选择切换的房间"
            style={{width: 300, marginTop: '10px'}}
            allowClear
            onChange={changeRoomSub}
          >
            {changeroomlist.map((item) => {
              return (
                <Option value={item.id} key={item.id}>
                  {item.room_address}
                </Option>
              );
            })}
          </Select>
        </Modal>

        <Modal
          visible={renewalVisible}
          title="续住办理"
          okText="确定"
          cancelText="取消"
          onCancel={handleCancel}
          onOk={() => {
            form
              .validateFields()
              .then((values) => {
                form.resetFields();
                onCreateXuzhu(values);
              })
              .catch((info) => {
                console.log('Validate Failed:', info);
              });
          }}
        >
          {renewalVisible ? (
            <Form form={form} layout="vertical" name="续住时间">
              <Form.Item name="reduce" label="请选择续住时间">
                <RangePicker disabledDate={disabledDate} />
              </Form.Item>
            </Form>
          ) : (
            <></>
          )}
        </Modal>

        <Modal
          title="房间已打扫完毕"
          visible={clearRoomVisible}
          onOk={() => clearroom('clear')}
          onCancel={handleCancel}
        >
          <p>房间打扫完毕 状态改变</p>
        </Modal>

        <Modal
          title="入住"
          visible={goinghome}
          onOk={() => {
            form
              .validateFields()
              .then((values) => {
                form.resetFields();
                onCreateUser(values);
              })
              .catch((info) => {
                console.log('Validate Failed:', info);
              });
          }}
          onCancel={handleCancel}
        >
          {goinghome ? (
            <Form form={form} layout="vertical" name="入住信息">
              <Form.Item key={Math.random()} name="userName" label="入住人姓名">
                <Input key={Math.random()} autocomplete="name" />
              </Form.Item>
              <Form.Item key={Math.random()} name="userInfo" label="身份证号">
                <Input key={Math.random()} maxlength="18" />
              </Form.Item>
            </Form>
          ) : (
            <></>
          )}
        </Modal>

        <Modal
          title="退房订单"
          visible={outRoom}
          onOk={clearroom}
          onCancel={handleCancel}
        >
          <p>确认退房操作 状态变为待打扫</p>
        </Modal>
      </RoomBox>
    </>
  );
}
